package com.zzh.springairobort.controller;

import com.zzh.springairobort.entity.request.PromptSessionIdRequest;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

/**
 * @author: zzh
 * @date: 2025/04/03 22:40:59
 * @version: 1.0
 */
@RestController
@RequestMapping("/chat/hospital/ai")
@CrossOrigin(origins = "*")
public class ChatHospitalAIController {

    private final ChatClient chatClient;



    public ChatHospitalAIController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder.build();
    }

    /**
     * 发送消息 AI 客服 记忆存储
     * @param promptSessionIdRequest 消息 + 会话ID
     * @return Flux<String>
     */
    @PostMapping(value = "/send" , produces = "text/plain;charset=UTF-8")
    public Flux<String> send(@RequestBody PromptSessionIdRequest promptSessionIdRequest) {
        //参数校验
        if (promptSessionIdRequest == null || promptSessionIdRequest.getMessage() == null || promptSessionIdRequest.getSessionId() == null) {
            return Flux.just("参数错误");
        }
        //获取消息
        String message = promptSessionIdRequest.getMessage();
        String chatId = promptSessionIdRequest.getSessionId();
        return chatClient.prompt()
                .user(message)
                //加一个环绕增强，传入会话id
                .advisors(a->a.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                .stream()
                .content()
                .map(content -> content.replace("<p>", "").replace("</p>", "\n"));  // 可选：在后端直接清理HTML标签
    }

}
